package com.qcby.demoforspringboot.aop;

import lombok.extern.apachecommons.CommonsLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Aspect
@Component
public class MethodCount {
    private Map<String,Integer> count= new HashMap<String,Integer>();
    @Pointcut("execution (* com.qcby.demoforspringboot.controller.*.*(..))")
    public void count() {
        System.out.println("切点方法执行");
    }
    @After("count()")
    public void afterCount() {
        System.out.println("方法执行后111111111");
    }
    @Around("count()")
    public Object methodExec(ProceedingJoinPoint pjp) {
        System.out.println("方法执行前");
        Signature signature = pjp.getSignature();
        String name = signature.getName();
        System.out.println(name);
        System.out.println(signature.getDeclaringTypeName());
        Object[] args = pjp.getArgs();
        for (Object arg : args) {
            System.out.println("aop arg:" + arg);

        }
        Object result = null;
        String key = signature.toLongString();
        System.out.println();
        count.put(key,count.getOrDefault(key,0)+1);
        Random random = new Random();
        int i = random.nextInt(10);
        if(i>5) {
            System.out.println("正常通过");
                try {
                    result = pjp.proceed();
                } catch (Throwable e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }

        }else {
            System.out.println("拒绝通过");
        }
        System.out.println("方法执行后");
        System.out.println(count);
        return result;
    }

}
